<?php
/**
 * Created by PhpStorm.
 * User: g
 * Date: 2018/3/14
 * Time: 13:08
 */

namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use think\Validate;
use app\index\validate\Valid;

class Jxsmh extends Controller
{

    public function _initialize(Request $request = null)
    {
        header('Access-Control-Allow-Origin:*');
    }
    /*获取经销商*/
    public function getjxs($id=null){
        $where=[];
        if($id){
            $where["j.id"]=$id;
        }
        $data=db("cg_jxs j")->join("cg_market_zoning z","j.zoning=z.id")
        ->join("cg_market_provice p","j.provice=p.id")
        ->join("cg_market_city c","j.city=c.id")
        ->where($where)->field("j.id,j.title,j.sn,z.title as zoning,p.title as provice,c.title as city,direct,import,j.isdel")->select();
        echo json_encode($data);
    }
    /*获取产品*/
    public function getpro($id=null){
        
            $where=[];
            if($id){
                $where["p.id"]=$id;
            }
            $data=db("pro_products")->where($where)->field("id,pro_no,pro_name,unit,weight,pro_sku,box_num,is_actived,is_deleted")->select();
       
        
        echo json_encode($data);
    }
    /*获取价格*/
    public function getprice($pid,$jid){
        $price=db("pro_price")->where(["pid"=>$pid])->value("factory");
        //echo 1;
        $gid=db("price_group_jxs pj")->join("pro_price_group p","pj.gid=p.id")->where("pj.jid=$jid")->value("pj.gid");
        if($gid){
            $now=date("Y-m-d");
            $gp=db("price_group_product")->where("pid=$pid and gid=$gid and start_time<='$now' and end_time>='$now'")->find();
            if($gp)
                $price=$gp["lingshou_price"];
               
        }
        echo $price;
            
        
    }
    //接收订单
    public function protoorder($oredr){
        $oredr=json_encode($order,true);
        Db::startTrans();
        try{
            $data["cusName"]=$order["jid"];
            $data["cusType"]=1;
            $jxs=db("cg_jxs")->where(["id"=>$data["cusName"]])->find();
            if($jxs){
                if($jxs["isdel"]){
                    echo json_encode(["success"=>false,"msg"=>"客户未激活"]);die;
                }else{
                    $data["khbh"]=$jxs["sn"];
                    $data["khmc"]=$jxs["title"];
                }
            }else{
                echo json_encode(["success"=>false,"msg"=>"客户不存在"]);die;
            }
            $data["shdz"]=$order["shdz"];
            $data["shr"]=$order["shr"];
            $data["dh"]=$order["shdh"];
            $data["jyfhrq"]=$order["jyfhrq"];
            $data["status"]=1;
            if(isset($data["zysx"]))
                $data["zysx"]=$order["zysx"];
            $data["ctime"]=time();
            $data["sn"]=$this->produceSN();;
            $data["yszje"]=$order["money"];
            $data["type_id"]=2;
            $detail=$order["detail"];
            $res1=db("cg_order")->insertGetId($data);
            $datade=[];
            if($detail){
                $num=0;
                foreach ($detail as $k => $v) {
                    $num++;
                    # code...
                    $tmp["kind"]=1;
                    $tmp["product"]=$detail[$k]["pid"];
                    $product=db("pro_products")->where(["id"=>$V["pid"]])->find();
                    if($product){
                        
                        $tmp["prod_sn"]=$product["pro_sn"];
                        $tmp["prod_name"]=$product["pro_name"];
                        $pbs=db("pro_brands pb")->join("pro_category pc","pc.brand_id=pb.id")->join("pro_series ps","ps.category_id=ps.id")
                        ->join("pro_sku sk","sk.series_id=ps.id")
                        ->where(["sk.id"=>$product["sku_id"]])->field("brand_name,category_name,series_name,sku_name")->find();
                        $tmp["brand"]=$pbs["brand_name"];
                        $tmp["category"]=$pbs["category_name"];
                        $tmp["series"]=$pbs["series_name"];
                        $tmp["sku"]=$pbs["sku_name"];
                        $tmp["unit"]=$product["unit"];
                    }else{
                        echo json_encode(["success"=>false,"msg"=>"产品不存在"]);die;
                    }
                    $tmp["num"]=$v["num"];
                    $tmp["ygj"]=$v["price"];
                    $tmp["xgj"]=$v["price"];
                    $tmp["ysje"]=$v["price"]*$v["num"];
                    //$tmp["dzsl"]=$v["zengnum"];
                    $tmp["order_id"]=$res1;
                    $tmp["sn"]=$num;
                    $datade[]=$tmp;
                }
                db("cg_order_list")->insertAll($datas);

            }else{
                echo json_encode(["success"=>false,"msg"=>"至少一条明细"]);die;
            }
        }catch (\Exception $e) {
            echo json_encode(["success"=>false,"msg"=>$e->getError()]);die;
        }
        echo json_encode(["success"=>true,"msg"=>"操作已成功","sn"=>$data["sn"]]);die;
    }
    //门户订货
    public function add($jid){
        $jxs=db("cg_jxs")->where("id=$jid")->find();
        //$this->assign("jxs",$jxs);
        $isbuhuo=db("system_param")->where("k='isTianJiaBuHuo'")->value('v');
        $this->assign("isbuhuo",$isbuhuo);
        $isbufei=db("system_param")->where("k='isTianJiaBuFei'")->value('v');
        $this->assign("isbufei",$isbufei);
        $order["khmc"]=$jxs["title"];$order["cusName"]=$jid;
        $order["jyfhrq"]="";
        $order["shdz"]=$jxs["bs_rcv_addr"];
        $order["shr"]=$jxs["bs_rcv_one"];
        $order["dh"]=$jxs["bs_rcv_phone"];
        $order["yszje"]=0;
        $order["yhPolicy"]=0;
        $order["zysx"]="";
        $order["id"]='';
        $this->assign("order",$order);
        $yhlist=$this->yhPolicy($jid);
        $this->assign("yhlist",$yhlist);
        $orderde=[];
        $this->assign("orderde",$orderde);
        return $this->fetch("add");
    }
    public function orderlist($jid){
        $data=db("cg_order")->where(["cusType"=>1,"cusName"=>$jid,"type_id"=>2])->order("id desc")->select();
        $order=[];
        foreach ($data as $k => $v) {
            # code...
            $tmp["sn"]=$v["sn"];
            $tmp["jine"]=$v["yszje"];
            $tmp["state"]=$v["status"];
            $tmp["yh"]=$v["yhPolicymc"];
            $tmp["id"]=$v["id"];
            $tmp["fhzt"]=$v["fhzt"];
            $tmp["shzt"]=$v["shzt"];
            $order[]=$tmp;
        }
        echo json_encode($order);die;
    }
    //门户修改
    public function updateorder($oid){

        $order=db("cg_order")->where(["id"=>$oid])->find();
        $this->assign("order",$order);
        $isbuhuo=db("system_param")->where("k='isTianJiaBuHuo'")->value('v');
        $this->assign("isbuhuo",$isbuhuo);
        $isbufei=db("system_param")->where("k='isTianJiaBuFei'")->value('v');
        $this->assign("isbufei",$isbufei);
        $yhlist=$this->yhPolicy($order["cusName"]);
        $this->assign("yhlist",$yhlist);
         $zj1 =0;
            $zj2  =0;
            $zj3  =0;
            $zj4 =0;
            $id=$oid;
            //查询销售订单明细
        $list = db('cg_order_list')->where(['order_id'=>$oid,'xslx'=>['in',[1,2]]])->select();
        foreach($list as $k=>$v){
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            //$v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            $zj1 += $v['num'];
            $zj2 += $v['dzsl'];
            $zj3 += $v['yje'];
            $zj4 += $v['ysje'];
            if($v['dyddmxid'])
                $v['dyddmxid'] = $order['sn'].'-'.db('cg_order_list')->where('id',$v['dyddmxid'])->value('sn');
            $list[$k] = $v;
        }
        $data['list'] = $list;

        //查询货补订单明细
        $list = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>3])->select();
        foreach($list as $k=>$v){
//            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
//            $v['prod_sn'] = db('pro_products')->where('id',$v['product'])->value('pro_no');
            $main_sn = db('cg_ti_hexiao_list t')->join('cg_ti_hexiao t2','t2.id=t.hx_id')->where('t.id',$v['hxdmxbh'])->value('t2.sn');
            $sub_sn = db('cg_ti_hexiao_list')->where('id',$v['hxdmxbh'])->value('sn');
            $v['hxdbh'] = $main_sn.'_'.$sub_sn;
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            $v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            $zj2 += $v['num'];
            $zj3 += $v['ysje'];
            $zj4 += $v['ysje'];
            $list[$k] = $v;
        }
        $data['huobu'] = $list;

        //查询补费订单明细
        $list2 = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>4])->select();
        $xj = 0;
        foreach($list2 as $k=>$v){
            $v['hxdbh'] = db('cg_ti_hexiao')->where('id',$v['hxdmxbh'])->value('sn');
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $list2[$k] = $v;
            $xj += $v['bfje'];
        }
        $data['bufei'] = $list2;

        
        $this->assign('xj',$xj);
        $zj1 = round($zj1,4);
        $zj2 = round($zj2,4);
        $zj3 = round($zj3,4);
        $zj4 = round($zj4,4);
        $this->assign([
            'zj1'=>$zj1,
            'zj2'=>$zj2,
            'zj3'=>$zj3,
            'zj4'=>$zj4,
        ]);
        $orderde=$data;
        $this->assign("data",$data);
        return $this->fetch("add");
    }
    //门户修改
    public function orderdetial($oid){

        $order=db("cg_order")->where(["id"=>$oid])->find();
        $this->assign("order",$order);
        $isbuhuo=db("system_param")->where("k='isTianJiaBuHuo'")->value('v');
        $this->assign("isbuhuo",$isbuhuo);
        $isbufei=db("system_param")->where("k='isTianJiaBuFei'")->value('v');
        $this->assign("isbufei",$isbufei);
        $yhlist=$this->yhPolicy($order["cusName"]);
        $this->assign("yhlist",$yhlist);
         $zj1 =0;
            $zj2  =0;
            $zj3  =0;
            $zj4 =0;
            $id=$oid;
            //查询销售订单明细
        $list = db('cg_order_list')->where(['order_id'=>$oid,'xslx'=>['in',[1,2]]])->select();
        foreach($list as $k=>$v){
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            //$v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            $zj1 += $v['num'];
            $zj2 += $v['dzsl'];
            $zj3 += $v['yje'];
            $zj4 += $v['ysje'];
            if($v['dyddmxid'])
                $v['dyddmxid'] = $order['sn'].'-'.db('cg_order_list')->where('id',$v['dyddmxid'])->value('sn');
            $list[$k] = $v;
        }
        $data['list'] = $list;

        //查询货补订单明细
        $list = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>3])->select();
        foreach($list as $k=>$v){
//            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
//            $v['prod_sn'] = db('pro_products')->where('id',$v['product'])->value('pro_no');
            $main_sn = db('cg_ti_hexiao_list t')->join('cg_ti_hexiao t2','t2.id=t.hx_id')->where('t.id',$v['hxdmxbh'])->value('t2.sn');
            $sub_sn = db('cg_ti_hexiao_list')->where('id',$v['hxdmxbh'])->value('sn');
            $v['hxdbh'] = $main_sn.'_'.$sub_sn;
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            $v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            $zj2 += $v['num'];
            $zj3 += $v['ysje'];
            $zj4 += $v['ysje'];
            $list[$k] = $v;
        }
        $data['huobu'] = $list;

        //查询补费订单明细
        $list2 = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>4])->select();
        $xj = 0;
        foreach($list2 as $k=>$v){
            $v['hxdbh'] = db('cg_ti_hexiao')->where('id',$v['hxdmxbh'])->value('sn');
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $list2[$k] = $v;
            $xj += $v['bfje'];
        }
        $data['bufei'] = $list2;

        
        $this->assign('xj',$xj);
        $zj1 = round($zj1,4);
        $zj2 = round($zj2,4);
        $zj3 = round($zj3,4);
        $zj4 = round($zj4,4);
        $this->assign([
            'zj1'=>$zj1,
            'zj2'=>$zj2,
            'zj3'=>$zj3,
            'zj4'=>$zj4,
        ]);
        $orderde=$data;
        $this->assign("data",$data);
        return $this->fetch();
    }
    //优惠政策
    public function yhPolicy($jxs_id){
        $city = db('cg_jxs')->where('id',$jxs_id)->value('city');
        $provice = db('cg_jxs')->where('id',$jxs_id)->value('provice');
        $zoning = db('cg_jxs')->where('id',$jxs_id)->value('zoning');
        //查询是否有渠道优惠政策
        $time = date('Y-m-d');
        $where="t.status=7 and t.is_revoke is null and ((area=1 and area_id like '%\"{$zoning}\"%') or (area=2 and area_id like '%\"{$provice}\"%') or (area=3 and area_id like '%\"{$city}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and td.start<='{$time}' and td.end>='{$time}'";
        $qdyhzc = db('cg_channel_preferential_policy t')->join("cg_channel_preferential_policy_cxfa td","td.p_id=t.id")
            ->where($where)->field('t.id,t.title,t.sn')->group("t.id")
            ->select();
        $data=[];
        foreach ($qdyhzc as $k => $v) {
            # code...
            $mingxi=db("cg_channel_preferential_policy_cxfa")->where("((area=1 and area_id like '%\"{$zoning}\"%') or (area=2 and area_id like '%\"{$provice}\"%') or (area=3 and area_id like '%\"{$city}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and start<='{$time}' and end>='{$time}' and p_id={$v["id"]}")->select();

            foreach ($mingxi as $km => $vm) {
                # code...
                $deid=db("cg_channel_preferential_policy_cxfa")->where("p_id={$v["id"]} and id<={$vm["id"]}")->count();
                $tmp["id"]=$vm["id"];
                $tmp["title"]=$v["title"].'-促销方案'.$deid;
                $data[]=$tmp;

            }
        }
        return $data;
    }
    public function add_Dd_detail(){
        if($_POST){
            $data = [];
            $data['kind'] = $this->request->post('kind');
            $data['product'] = $this->request->post('product');
            $data['num'] = $this->request->post('num');
            $data['unit'] = $this->request->post('unit');
            $data['prod_sn'] = $this->request->post('prod_sn');
            $data['ygj'] = $this->request->post('ygj');
            $data['xgj'] = $this->request->post('xgj');
            $data['yje'] = $this->request->post('yje');
            $data['ysje'] = $this->request->post('ysje');
            $dzcp = $this->request->post('dzcp');
            $dzsl = $this->request->post('dzsl');
            $dz_unit = $this->request->post('dz_unit');
            $dz_cpbm = $this->request->post('dz_cpbm');
            $dz_ygj = $this->request->post('dz_ygj');
            $dz_xgj = $this->request->post('dz_xgj');
            $dz_yje = $this->request->post('dz_yje');
            $dz_ysje = $this->request->post('dz_ysje');
           
            $data['beizhu'] = $this->request->post('beizhu');
            $data['order_id'] = $this->request->post('order_id');

            $valid = new Valid([
                'kind|类型'=>'require',
                'product|订货产品'=>'require',
                'num|订货数量'=>'require|number',
                'xgj|订货产品现供价'=>['require','jine'],
                'dz_xgj|搭赠产品现供价'=>['jine'],
               
            ]);
            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }

            //验证搭赠数量是否超过金额的系统参数%限制
            $limit = db('system_param')->where(['t'=>0,'k'=>'keDaPercent'])->value('v');
            if(!$data['order_id']&&$dz_ysje/$data['ysje']*100>$limit){
                echo json_encode(['success'=>false,'msg'=>'搭赠+补货+补费金额不能超过订单销售额的'.$limit.'%']);die;
            }elseif($data['order_id']){
                //搭赠金额
                $dzje = db('cg_order_list')->where(['order_id'=>$data['order_id'],'dzsl'=>['>',0],'xslx'=>2])->sum('ysje');
                $je = db('cg_order_list')->where(['order_id'=>$data['order_id'],'dzsl'=>['exp','is null'],'xslx'=>1])->sum('ysje');
                $hbje = db('cg_order_list')->where(['order_id'=>$data['order_id'],'xslx'=>3])->sum('ysje');
                $bfje = db('cg_order_list')->where(['order_id'=>$data['order_id'],'xslx'=>4])->sum('bfje');
                $dzze = $dzje+$hbje+$bfje+$dz_ysje;
                $zje = $je+$data['ysje'];
                if($dzze/$zje*100>$limit){
                    echo json_encode(['success'=>false,'msg'=>'搭赠+补货+补费金额不能超过订单销售额的'.$limit.'%']);die;
                }
            }

            if($dz_ysje){ //验证渠道优惠政策
                $yhpolicy = $this->request->post('yhPolicy');
                if($yhpolicy){
                    $estiGiftCost = db('cg_channel_preferential_policy')->where('id',$yhpolicy)->value('estiGiftCost');
                    if($data['order_id'])
                        $dz_ysje2 = db('cg_order_list')->where(['order_id'=>$data['order_id'],'dzsl'=>['>',0]])->value('ysje');
                    else
                        $dz_ysje2 = 0;
                    if(($dz_ysje2+$dz_ysje) > $estiGiftCost){
                        echo json_encode(['success'=>false,'msg'=>'搭赠应收金额不能超过渠道优惠政策预计搭赠产生的费用'.$estiGiftCost.'元']);die;
                    }
                }
            }

            if(!$data['order_id']){

                $d = [];
                $d['sn'] = $this->produceSN();
                //$d['sqr'] = session('employee_id');
                //$d['sqrmc'] = db('employee')->where('id',session('employee_id'))->value('em_name');
                $d["type_id"]=2;
                $d['sqrq'] = time();
                $d['cusType'] = 1;
                $d['cusName'] = $this->request->post('cusName');
                if($d['cusType']==1){
                    $d['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t.id=t2.zoning')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t.id=t2.provice')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['city'] = db('cg_market_city t')->join('cg_jxs t2','t.id=t2.city')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['khbh'] = db('cg_jxs')->where('id',$d['cusName'])->value('sn');
                    $d['khmc'] = db('cg_jxs')->where('id',$d['cusName'])->value('title');
                }else{
                    $d['zoning'] = db('cg_market_zoning t')->join('cg_net t2','t.id=t2.zoning')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['provice'] = db('cg_market_provice t')->join('cg_net t2','t.id=t2.provice')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['city'] = db('cg_market_city t')->join('cg_net t2','t.id=t2.city')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['khbh'] = db('cg_net')->where('id',$d['cusName'])->value('sn');
                    $d['khmc'] = db('cg_net')->where('id',$d['cusName'])->value('title');
                }
                $d['fpType'] = $this->request->post('fpType');
                $d['yhPolicy'] = $this->request->post('yhPolicy');
                $d['yhPolicymc'] = db('cg_channel_preferential_policy')->where('id',$d['yhPolicy'])->value('title');
                $d['shdz'] = $this->request->post('shdz');
                $d['shr'] = $this->request->post('shr');
                $d['dh'] = $this->request->post('dh');
                $d['jyfhrq'] = $this->request->post('jyfhrq');
                $d['status'] = 1;
                $d['zysx'] = $this->request->post('zysx');
                $data['order_id'] = db('cg_order')->insertGetId($d);
                $basic = 0;

            }else{

                //验证是否已经存在此明细
                $ishas = db('cg_order_list')->where(['order_id'=>$data['order_id'],'product'=>$data['product'],'dzsl'=>['exp','is null']])->count();
                if($ishas){
                    $pro_name = db('pro_products')->where('id',$data['product'])->value('pro_name');
                    echo json_encode(['success'=>false,'msg'=>'本订单中已经存在名称为：'.$pro_name]);die;
                }

                $basic = db('cg_order_list')->where('order_id',$data['order_id'])->max('sn'); //编号递增开始位置基础

            }
            $data['sn'] = $basic+1;
            if($data['kind']==1){
                $data['brand'] = db('pro_brands t')->join('pro_category t2','t.id=t2.brand_id')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t.brand_name');
                $data['category'] = db('pro_category t2')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t2.category_name');
                $data['series'] = db('pro_series t3')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t3.series_name');
                $data['sku'] = db('pro_sku t4')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t4.sku_name');
                $data['prod_name'] = db('pro_products')->where('id',$data['product'])->value('pro_name');
            }else{
                $data['prod_name'] = db('pro_materials')->where(['id'=>$data['product'],'m_type'=>2])->value('material_name');
            }
            $data['xslx'] = 1;
            $bool = db('cg_order_list')->insertGetId($data);
            if(false!==$bool){
                if($dzsl>0){
                    $insert = [];
                    $insert['dyddmxid'] = $bool;
                    $insert['kind'] = $data['kind'];
                    $insert['product'] = $dzcp;
                    $insert['dzsl'] = $dzsl;
                    $insert['unit'] = $dz_unit;
                    if($data['kind']==1) {
                        $insert['brand'] = db('pro_brands t')->join('pro_category t2','t.id=t2.brand_id')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$dzcp)->value('t.brand_name');
                        $insert['category'] = db('pro_category t2')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$dzcp)->value('t2.category_name');
                        $insert['series'] = db('pro_series t3')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$dzcp)->value('t3.series_name');
                        $insert['sku'] = db('pro_sku t4')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$dzcp)->value('t4.sku_name');
                        $insert['prod_name'] = db('pro_products')->where('id',$dzcp)->value('pro_name');
                    }else{
                        $data['prod_name'] = db('pro_materials')->where(['id'=>$dzcp,'m_type'=>2])->value('material_name');
                    }
                    $insert['prod_sn'] = $dz_cpbm;

                    $insert['ygj'] = $dz_ygj;
                    $insert['xgj'] = $dz_xgj;
                    $insert['yje'] = $dz_yje;
                    $insert['ysje'] = $dz_ysje;
                    $insert['xsry'] = $this->request->post('xsry');
                    $insert['ssbm'] = $this->request->post('ssbm');
                    $insert['beizhu'] = $this->request->post('beizhu');
                    $insert['order_id'] = $data['order_id'];
                    $insert['sn'] = $basic+2;
                    $insert['xslx'] = 2;
                    db('cg_order_list')->insert($insert);
                }
                $ysje = db('cg_order_list')->where('order_id',$data['order_id'])->sum('ysje');
                $qdyhje = db('cg_order_list')->where('order_id',$data['order_id'])->sum('qdyhje');
                $bf = db('cg_order_list')->where(['order_id'=>$data['order_id'],'xslx'=>4])->sum('ysje');
                $ysje = $ysje-$qdyhje-$bf;
                db('cg_order')->where('id',$data['order_id'])->update(['yszje'=>$ysje]);
                echo json_encode(['success'=>true,'msg'=>'保存成功','id'=>$data['order_id']]);die;
            }else{
                echo json_encode(['success'=>false,'msg'=>'保存失败']);die;
            }
            die;
        }

       // $uid = session('employee_id');
       // $uname = db('employee')->where('id',$uid)->value('em_name');
        //$de_name = db('department t')->join('department_employee t2','t2.department_id=t.id')->where('t2.employee_id',$uid)->value('de_name');
       // $de_id = db('department_employee')->where('employee_id',$uid)->value('department_id');
        /*$this->assign([
            'uid'=>$uid,
            'uname'=>$uname,
            'de_name'=>$de_name,
            'de_id'=>$de_id
        ]);*/

        /*//查询优惠政策搭赠限额
        $yhpolicy = $this->request->param('yhpolicy');
        if($yhpolicy){
            $estiGiftCost = db('cg_channel_preferential_policy')->where('id',$yhpolicy)->value('estiGiftCost');
            $this->assign('estiGiftCost',$estiGiftCost);
        }*/
        return $this->fetch();
    }
      public function produceSN(){
        //生成编号
        $max = db('cg_order')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }
    public function producemxSN($order_id){
        //生成编号
        $max = db('cg_order_list')->where(['order_id'=>$order_id])->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = 1;
        }
        return $insert_sn;
    }
     /**
     * 查询渠道优惠政策限制并计算订单金额
     */
    public function qdyhzcxz(){
        $qdyh_id = $this->request->param('qdyh_id');
        $order_id = $this->request->param('order_id');
        $qdyh_name=db('cg_channel_preferential_policy p')->join("cg_channel_preferential_policy_cxfa pd","pd.p_id=p.id")->where('pd.id',$qdyh_id)->value('p.title');
        $qid=db("cg_channel_preferential_policy_cxfa")->where(["id"=>$qdyh_id])->value("p_id");
        $fanganno=db("cg_channel_preferential_policy_cxfa")->where("id<=$qdyh_id and p_id=$qid")->count();
        $bool = db('cg_order')
            ->where('id',$order_id)
            ->update([
                'yhPolicy'=>$qdyh_id,
                'yhPolicymc'=>$qdyh_name.'-促销方案'.$fanganno
            ]);
       // echo $bool;exit;
        //订单明细应用渠道优惠规则
        $khxx = db('cg_order')->where(['id'=>$order_id])->field('cusType,cusName')->find();
        if($khxx['cusType']==1){ //经销商
            //查询经销商所在的大区省份城市
            $jxs = $khxx['cusName'];
            $city = db('cg_jxs')->where('id',$khxx['cusName'])->value('city');
            $provice = db('cg_jxs')->where('id',$khxx['cusName'])->value('provice');
            $zoning = db('cg_jxs')->where('id',$khxx['cusName'])->value('zoning');

        }else{ //网点
            $jxs = db('cg_net t')->join('cg_system t2','t2.id=t.system_id')->where('t.id',$khxx['cusName'])->value('t2.jxs');
            $city = db('cg_jxs')->where('id',$jxs)->value('city');
            $provice = db('cg_jxs')->where('id',$jxs)->value('provice');
            $zoning = db('cg_jxs')->where('id',$jxs)->value('zoning');
        }

        //查询渠道优惠政策的明细
        $qdmx2 = Db::query('select sfzd,product,product_id,yhlx,chzk_unit,chzk_reach,chzk_down,chzk_limit,agdjch_unit,agdjch_reach,agdjch_down,agdjch_limit,shdz_unit,shdz_reach,shdz_gift,shdz_limit,shmj_unit,shmj_reach,shmj_down,shmj_limit,chfd_unit,chfd_reach,chfd_down,chfd_limit 
from cg_channel_preferential_policy_cxfa 
where id='.$qdyh_id.' 
and start <= \''.date('Y-m-d').'\' 
and `end` >=\''.date('Y-m-d').'\' 
and ((area=1 and area_id like \'%"'.$zoning.'"%\') or (area=2 and area_id like \'%"'.$provice.'"%\') or (area=3 and area_id like \'%"'.$city.'"%\')or (area=4 and area_id like \'%"'.$jxs.'"%\'))');//非整单优惠政策明细信息
        //print_r($qdmx2);exit;
        /**
         * 明细套用渠道优惠政策--start
         */
        $mx = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>1])->select();
        $qdyhje = db('cg_order_list')->where(['order_id'=>$order_id])->sum('qdyhje');
        db('cg_order')->where(['id'=>$order_id])->setInc('yszje',$qdyhje);
       // db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>1])->update(['qdyhje'=>0,'qdyhms'=>null]);
        db('cg_order_list')->query("update cg_order_list set qdyhje=0,qdyhms=null,ysje=yje where order_id=$order_id and xslx=1");
        //echo db('cg_order_list')->getLastSql();exit;
        db('cg_order_list')->where(['order_id'=>$order_id,'sfqdzp'=>1])->delete();


        foreach($mx as $k=>$v){
            $v['id'];
            $ysje = $v['yje'];
            $ysjes=$ysje;
            //echo $ysje;exit;
            $qdyhms = '';
            $num=$v['num'];
            $v['kind']==1;
            $product = $v['product'];
            $sku = db('pro_products')->where('id',$v['product'])->value('sku_id');
            $series_id = db('pro_sku')->where('id',$sku)->value('series_id');
            $category_id = db('pro_series')->where('id',$series_id)->value('category_id');
            $brand_id = db('pro_category')->where('id',$category_id)->value('brand_id');
            foreach($qdmx2 as $k2=>$v2){
                if($v2['sfzd'] == 0){ //非整单
                    //判断产品是否符合渠道优惠政策的条件
                    if(
                        ($v2['product']==5&&in_array($product,unserialize($v2['product_id'])))
                        || ($v2['product']==1&&in_array($brand_id,unserialize($v2['product_id'])))
                        || ($v2['product']==2&&in_array($category_id,unserialize($v2['product_id'])))
                        || ($v2['product']==3&&in_array($series_id,unserialize($v2['product_id'])))
                        || ($v2['product']==4&&in_array($sku,unserialize($v2['product_id'])))
                    ){
                        if(in_array(3,unserialize($v2['yhlx']))){ //出货折扣
                            $reach = unserialize($v2['chzk_reach']);
                            $down = unserialize($v2['chzk_down']);
                            $limit = unserialize($v2['chzk_limit']);
                            $unit = $v2['chzk_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                   // echo $reach[$key];exit;
                                    $yhje = round($ysjes*$down[$key]/100,2);

                                    if($limit[$key]){
                                        if($yhje>$limit[$key]){
                                            $yhje = $limit[$key];
                                        }
                                    }
                                    //echo $yhje;exit;
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元 '.$down[$key].'%OFF，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元 '.$down[$key].'%OFF，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);
                                   
                                    $ysje = $ysje-$yhje;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $jiannum=round($num*$down[$key]/100,2);
                                    if($limit[$key]){
                                        if($jiannum>$limit[$key]){
                                            $jiannum= $limit[$key];
                                        }
                                    }
                                    $yhje = round($jiannum*$v["xgj"],2);
                                    //echo $yhje;
                                    
                                     $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位)'.$down[$key].'%OFF，限量'.$limit[$key].'（发运单位）;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'（发运单位)'.$down[$key].'%OFF，限量'.$limit[$key].'（发运单位）;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);

                                  
                                    $ysje = $ysje-$yhje;
                                }
                            }
                        }

                        if(in_array(4,unserialize($v2['yhlx']))){ //按固定价出货
                            $reach = unserialize($v2['agdjch_reach']);
                            $down = unserialize($v2['agdjch_down']);
                            $limit = unserialize($v2['agdjch_limit']);
                            $unit = $v2['agdjch_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $yhje = $num*$down[$key];
                                    $sxje = $ysje-$yhje; //省下金额
                                    //echo $sxje;exit;
                                    if($limit[$key]){
                                         if($sxje>$limit[$key]){
                                            $sxje = $limit[$key];
                                        }
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元按'.$down[$key].'元出货，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元按'.$down[$key].'元出货，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$sxje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$sxje);

                                   
                                    $ysje = $ysje-$sxje;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    //echo $limit[$key];
                                    $limit[$key];
                                    if($limit[$key]){
                                        if($num>$limit[$key]){
                                            $sxje = ($v['xgj']-$down[$key])*$limit[$key];
                                        }else{ //完全按照新价格计算优惠金额
                                            $yhje = $num*$down[$key];
                                            $sxje = $ysjes-$yhje; //省下金额

                                        }
                                    }else{
                                        $yhje = $num*$down[$key];
                                        $sxje = $ysjes-$yhje; //省下金额
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位）按'.$down[$key].'（元/发运单位）出货，限量'.$limit[$key].'（发运单位）;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'（发运单位）按'.$down[$key].'（元/发运单位）出货，限量'.$limit[$key].'（发运单位）;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$sxje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$sxje);


                                    $ysje = $ysje-$sxje;
                                }
                            }
                        }

                        if(in_array(5,unserialize($v2['yhlx']))){ //随货搭赠
                            //echo 5;
                            $reach = unserialize($v2['shdz_reach']);
                            $down = unserialize($v2['shdz_gift']);
                            $limit = unserialize($v2['shdz_limit']);
                            $unit = $v2['shdz_unit'];
                            if($unit=='元'){

                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $gift = $this->unescape($down[$key]);
//                                $gift = str_replace('"',"'",$gift);

                                    $gift = json_decode($gift);
                                    $zongbujin=0;

                                    foreach ($gift as $gk => $gv) {
                                        # code...
                                        $zongbujin+=$gv->total;
                                    }
                                    $buhuojine=round($ysjes/$reach[$key],2)*$zongbujin;
                                    if($limit[$key]){
                                        $buhuojine=$buhuojine<=$limit[$key]?$buhuojine:$limit[$key];
                                    }
                                    $beishu=round($buhuojine/$zongbujin,2);
                                    //echo $beishu;//exit;
                                    $zj = 0;
                                    foreach($gift as $gk => $gv){
                                       // echo 1;
                                        $ins = [];
                                        $ins['kind'] = $gv->wy+1;

                                        $ins['product'] = $gv->product;

                                        if($gv->wy==0){
                                            $ins['prod_sn'] = db('pro_products')->where('id',$gv->product)->value('pro_no');
                                            $ins['sku'] = db('pro_products')->where('id',$gv->product)->value('sku_id');
                                            $ins['series'] = db('pro_sku')->where('id',$ins['sku'])->value('series_id');
                                            $ins['category'] = db('pro_series')->where('id',$ins['series'])->value('category_id');
                                            $ins['brand'] = db('pro_category')->where('id',$ins['category'])->value('brand_id');
                                        }else{
                                            $ins['prod_sn'] = db('pro_materials')->where('id',$gv->product)->value('material_no');
                                        }

                                        $ins['prod_name'] = $gv->product_title;
                                        $ins['dzsl'] = floor($gv->num*$beishu);
                                        $ins['unit'] = $gv->unit;
                                        $ins['ygj'] = $gv->price;
                                        $ins['xgj'] = $gv->price;
                                        $ins['yje'] = floor($gv->num*$beishu)*$gv->price;
                                        $ins['order_id'] = $v['order_id'];
                                        $ins['dyddmxid'] = $v['id'];
                                        $ins['xslx'] = 2;
                                        $ins['ysje'] = 0;
                                        $ins['sfqdzp'] = 1;
                                        $ins['sn'] = $this->producemxSN($v['order_id']);

                                        $zj += $ins['yje'];
                                        if($limit[$key]){
                                            if($zj>$limit[$key]){
                                                continue;
                                            }
                                        }
                                        

                                        db('cg_order_list')->insert($ins);
                                    }
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $gift = $this->unescape($down[$key]);

                                    $gift = json_decode($gift);
                                    $jiannum=$num;
                                    if($limit[$key]){
                                        $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                    }
                                    $beishu=floor($jiannum/$reach[$key]);
                                    //echo $beishu;
                                    $zj = 0;
                                    foreach($gift as $gk => $gv){
                                        $ins['kind'] = $gv->wy+1;

                                        $ins['product'] = $gv->product;
                                        if($gv->wy==0){
                                            $ins['prod_sn'] = db('pro_products')->where('id',$gv->product)->value('pro_no');
                                            $ins['sku'] = db('pro_products')->where('id',$gv->product)->value('sku_id');
                                            $ins['series'] = db('pro_sku')->where('id',$ins['sku'])->value('series_id');
                                            $ins['category'] = db('pro_series')->where('id',$ins['series'])->value('category_id');
                                            $ins['brand'] = db('pro_category')->where('id',$ins['category'])->value('brand_id');
                                        }else{
                                            $ins['prod_sn'] = db('pro_materials')->where('id',$gv->product)->value('material_no');
                                        }

                                        $ins['prod_name'] = $gv->product_title;
                                        $ins['dzsl'] = $gv->num*$beishu;
                                        $ins['unit'] = $gv->unit;
                                        $ins['ygj'] = $gv->price;
                                        $ins['xgj'] = $gv->price;
                                        $ins['yje'] = $gv->total*$beishu;
                                        $ins['order_id'] = $v['order_id'];
                                        $ins['dyddmxid'] = $v['id'];
                                        $ins['xslx'] = 2;
                                        $ins['ysje'] = 0;
                                        $ins['sfqdzp'] = 1;
                                        $ins['sn'] = $this->producemxSN($v['order_id']);
                                        $zj += $ins['yje'];
                                        
                                        db('cg_order_list')->insert($ins);
                                    }

                                }
                            }
                        }

                        if(in_array(1,unserialize($v2['yhlx']))){ //随货满减
                            
                            $reach = unserialize($v2['shmj_reach']);
                            $down = unserialize($v2['shmj_down']);
                            $limit = unserialize($v2['shmj_limit']);
                            $unit = $v2['shmj_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $jianjine=floor($ysjes/$reach[$key])*$down[$key];
                                    //echo $jianjine;exit;
                                    if($limit[$key]){
                                        $jianjine=$jianjine<=$limit[$key]?$jianjine:$limit[$key];
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jianjine);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jianjine);


                                    $ysje = $ysje-$jianjine;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $jiannum=floor($num/$reach[$key])*$down[$key];

                                    if($limit[$key]){
                                        $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                    }
                                    //echo $jiannum;exit;
                                    $jian =$jiannum*$v['xgj'];
                                     $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jian);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jian);

                                    
                                    $ysje = $ysje-$jian;
                                }
                            }
                        }

                        if(in_array(2,unserialize($v2['yhlx']))){ //出货返点

                            $reach = unserialize($v2['chfd_reach']);
                            $down = unserialize($v2['chfd_down']);
                            $limit = unserialize($v2['chfd_limit']);
                            $unit = $v2['chfd_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $yhje = round($ysjes*$down[$key]/100,2);
                                    if($limit[$key]){
                                        if($yhje>$limit[$key]){
                                            $yhje = $limit[$key];
                                        }
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);

                                    $ysje = $ysje-$yhje;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                   $jiannum=round($num*$down[$key]/100,2);
                                    //echo $jiannum;exit;
                                    if($limit[$key]){
                                        $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                    }
                                    
                                    $yhje =$jiannum*$v['xgj'];
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);

                                    
                                    $ysje = $ysje-$yhje;
                                }
                            }
                        }
                        $qdyhzcje = db('cg_order_list')->where('order_id',$v['order_id'])->sum('qdyhje');
                        db('cg_order')
                            ->where('id',$v['order_id'])
                            ->setDec('yszje',$qdyhzcje);
                    }
                }else{ //整单

                    if(in_array(1,unserialize($v2['yhlx']))){ //随货满减

                        $reach = unserialize($v2['shmj_reach']);
                        $down = unserialize($v2['shmj_down']);
                        $limit = unserialize($v2['shmj_limit']);
                        $unit = $v2['shmj_unit'];//echo $ysje;exit;
                       // echo 1;exit;
                        if($unit=='元'){
                            $max = $this->jstj($reach,$ysjes);

                            if($max){
                                $key=array_search($max ,$reach);
                                $down[$key];
                                $limit[$key];

                                $jisuanjine=floor($ysjes/$reach[$key])*$down[$key];
                                if($limit[$key])
                                    $jisuanjine=$jisuanjine<=$limit[$key]?$jisuanjine:$limit[$key];
                                //echo $jisuanjine;exit;
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                }

                                db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                               
                                db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jisuanjine);
                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jisuanjine);
                                $ysje = $ysje-$jisuanjine;
                            }
                        }else{ //发运单位
                            echo 1;
                            $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                            if($max){
                                $key=array_search($max ,$reach);
                                $down[$key];
                                $limit[$key];
                                $jiannum=floor($num/$reach[$key])*$down[$key];

                                if($limit[$key]){
                                    $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                }
                                //echo $jiannum;exit;
                                $jian =$jiannum*$v['xgj'];
                               //echo $jian.'|';
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                }
                                db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jian);
                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jian);

                                $ysje = $ysje-$jian;
                            }
                        }
                    }

                    if(in_array(2,unserialize($v2['yhlx']))){ //出货返点
                        
                        $reach = unserialize($v2['chfd_reach']);
                        $down = unserialize($v2['chfd_down']);
                        $limit = unserialize($v2['chfd_limit']);
                        $unit = $v2['chfd_unit'];
                        //echo $ysje;exit;
                        //echo 2;exit;
                        if($unit=='元'){
                            $max = $this->jstj($reach,$ysjes);

                            if($max){
                                $key=array_search($max ,$reach);
                                $down[$key];
                                $limit[$key];
                                $yhje = round($ysjes*$down[$key]/100,2);
                                //echo $yhje;exit;
                                if($limit[$key]){
                                    if($yhje>$limit[$key]){
                                        $yhje = $limit[$key];
                                    }
                                }
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                }

                                db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                //echo $yhje;exit;
                                db('cg_order_list')->where("id={$v["id"]}")->setInc('qdyhje',$yhje);//echo 1;exit;

                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);
                                $ysje = $ysje-$yhje;
                            }
                        }else{ //发运单位

                            $max = $this->jstj2($reach,$ysjes,$v['xgj']);
                            //echo $max;exit;
                            if($max){

                                $key=array_search($max ,$reach);

                                $down[$key];
                                $limit[$key];
                                $jiannum=round($num*$down[$key]/100,2);
                                //echo $jiannum;exit;
                                if($limit[$key]){
                                    $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                }
                                
                                $yhje =$jiannum*$v['xgj'];
                                //echo $yhje.'|';
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                }
                                 db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);
                                $ysje = $ysje-$yhje;
                            }
                        }
                    }

                    $qdyhzcje = db('cg_order_list')->where('order_id',$v['order_id'])->sum('qdyhje');
                    $oid=$v["order_id"];
                    $je = db('cg_order_list')->where(['order_id'=>$oid])->sum('ysje');
            db('cg_order')->where(['id'=>$oid])->update(['yszje'=>$je]);
                }

            }
        }
        /**
         * 明细套用渠道优惠政策--end
         */

        if($bool !== false){
            echo json_encode(['success'=>true,'msg'=>'ok']);die;
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);die;
        }
    }
     //计算最大满数
    public function jstj($chzk_reach,$ysje){
        if(count($chzk_reach)==0){
            return false;
        }else{
            $max = max($chzk_reach);

            if($ysje>=$max){
                return $max;
            }else{
                $key=array_search($max ,$chzk_reach);
                array_splice($chzk_reach,$key,1);
                $this->jstj($chzk_reach,$ysje);
            }
        }
    }
    //计算最大满数--按照发运单位
    /**
     * @param $chzk_reach
     * @param $ysje
     * @param $xgj
     * @return bool|mixed
     */
    public function jstj2($chzk_reach,$ysje,$xgj){
        if(count($chzk_reach)==0){
            return false;
        }else{
            $max = max($chzk_reach);

            if($ysje>=$max*$xgj){
                return $max;
            }else{
                $key=array_search($max ,$chzk_reach);
                array_splice($chzk_reach,$key,1);
                $this->jstj($chzk_reach,$ysje,$xgj);
            }
        }
    }
     public function clearyh($oid){
        try{
             $bool = db('cg_order')->where('id',$oid)->update(['yhPolicy'=>0,'yhPolicymc'=>null]);
            $qdyhje = db('cg_order_list')->where(['order_id'=>$oid])->sum('qdyhje');
            db('cg_order')->where(['id'=>$oid])->setInc('yszje',$qdyhje);
           
            db('cg_order_list')->query("update cg_order_list set qdyhje=0,qdyhms=null,ysje=yje where order_id=$oid and xslx=1");
           
            db('cg_order_list')->where(['order_id'=>$oid,'sfqdzp'=>1])->delete();
            $je = db('cg_order_list')->where(['order_id'=>$oid])->sum('ysje');
            db('cg_order')->where(['id'=>$oid])->update(['yszje'=>$je]);
        }catch (\Exception $e) {
             echo json_encode(['success'=>false,'msg'=>$e->getMessage()]);die;
        }
        echo json_encode(['success'=>true,'msg'=>'ok']);die;
        
        
    }
    public function deDetail(){
        $id = $this->request->param('id');

        $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
        $bool = db('cg_order_list')->where('id',$id)->delete();

        $yszje = db('cg_order_list')->where('order_id',$order_id)->sum('ysje');
        $qdyhje = db('cg_order_list')->where('order_id',$order_id)->sum('qdyhje');
        $bfzje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
        $yszje = floatval($yszje)-floatval($qdyhje)-floatval($bfzje);
        $yszje = round($yszje,2);
         $je = db('cg_order_list')->where(['order_id'=>$order_id])->sum('ysje');
            db('cg_order')->where(['id'=>$order_id])->update(['yszje'=>$je]);
        if(false !== $bool){
            echo json_encode(['success'=>true,'msg'=>'删除成功']);die;
        }else{
            echo json_encode(['success'=>false,'msg'=>'false']);die;
        }
    }
    //修改明细
    public function upDetail(){
        $id = $this->request->param('id');
        if($_POST){
            $data = Request::instance()->post();

            if(isset($data['num'])){
                $valid = new Valid([
                    'kind|类型'=>'require',
                    'product|订货产品'=>'require',
                    'num|订货数量'=>'require|number',
                    'xgj|订货产品现供价'=>['require','jine'],
                    
                ]);
            }else{
                $valid = new Valid([
                    'kind|类型'=>'require',
                    'product|搭赠产品'=>'require',
                    'dzsl|搭赠数量'=>'require|number',
                    'xgj|搭赠产品现供价'=>['require','jine'],
                    
                ]);
            }

            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }

            //验证搭赠数量是否超过金额的系统参数%限制
            $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
            //限制
            $limit = db('system_param')->where(['t'=>0,'k'=>'keDaPercent'])->value('v');
            //已经搭赠的金额
            $dzje = db('cg_order_list')->where(['order_id'=>$order_id,'dzsl'=>['>',0],'id'=>['<>',$id],'xslx'=>2])->sum('ysje');
            //已经订购的金额
            $je = db('cg_order_list')->where(['order_id'=>$order_id,'dzsl'=>['exp','is null'],'id'=>['<>',$id],'xslx'=>1])->sum('ysje');
            //货补金额
            $hbje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>3])->sum('ysje');
            //补费金额
            $bfje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
            if(isset($data['dzsl'])){ //搭赠
                $dz = $dzje+$hbje+$bfje+$data['ysje'];
                $zje = $dz+$je;
                if($dz/$zje*100>$limit){
                    echo json_encode(['success'=>false,'msg'=>'搭赠+补货+补费金额不能超过订单销售额的'.$limit.'%']);die;
                }
            }else{ //订购
                $dz = $dzje+$hbje+$bfje;
                $zje = $dz+$je+$data['ysje'];
                if($dz/$zje*100>$limit){
                    echo json_encode(['success'=>false,'msg'=>'搭赠+补货+补费金额不能超过订单销售额的'.$limit.'%']);die;
                }
            }

            $data['unit'] = $this->request->param('unit');
            $data['prod_sn'] = $this->request->param('prod_sn');
            $data['prod_name'] = db('pro_products')->where('id',$data['product'])->value('pro_name');
            $data['brand'] = db('pro_brands t')->join('pro_category t2','t.id=t2.brand_id')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t.brand_name');
            $data['category'] = db('pro_category t2')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t2.category_name');
            $data['series'] = db('pro_series t3')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t3.series_name');
            $data['sku'] = db('pro_sku t4')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t4.sku_name');
           
            $data['beizhu'] = $this->request->post('beizhu');

            $bool = db('cg_order_list')->where('id',$id)->update($data);

            $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
            $yszje = db('cg_order_list')->where('order_id',$order_id)->sum('ysje');
            $qdyhje = db('cg_order_list')->where('order_id',$order_id)->sum('qdyhje');
            $bfzje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
            $yszje = $yszje-$qdyhje-$bfzje;
            $yszje = round($yszje,2);
             $je = db('cg_order_list')->where(['order_id'=>$order_id])->sum('ysje');
            db('cg_order')->where(['id'=>$order_id])->update(['yszje'=>$je]);

            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'保存成功']);die;
            }else{
                echo json_encode(['success'=>false,'msg'=>'保存失败']);die;
            }
            die;
        }
        $data = db('cg_order_list')->where('id',$id)->find();
        $data['product_name'] = db('pro_products')->where('id',$data['product'])->value('pro_name');
       
        $this->assign('data',$data);
        return $this->fetch();
    }

}